//
//  Man.m
//  NSRunTimeDemo
//
//  Created by CPZX010 on 16/9/22.
//  Copyright © 2016年 谢昆鹏. All rights reserved.
//

#import "Man.h"
#import <objc/message.h>
#import "Person.h"


@implementation Man
+ (void)load {
    Class class =  [Person class];
    Method person_Instance_eat = class_getInstanceMethod(class, @selector(resolveInstanceMethod:));
    Method man_Instance_eat = class_getInstanceMethod(self, @selector(resolveInstanceMethod:));
    method_exchangeImplementations(person_Instance_eat, man_Instance_eat);

}

void personEat (id self, SEL sel) {
    NSLog(@"personEATing........");
    NSLog(@"%@ %@", self, NSStringFromSelector(sel));
}

void manEat (id self, SEL sel) {
    NSLog(@"manEATing.......");
    NSLog(@"%@ %@", self, NSStringFromSelector(sel));
}

/**
 *  当一个对象添加了没有实现的方法时会调用此方法处理, 并把对应方法表传递过来
 *
 *  @param sel 想要添加的方法
 *
 *  @return 判断为实现的方法是不是我们想要动态添加的方法
 */
+ (BOOL)resolveClassMethod:(SEL)sel {
    if (sel == NSSelectorFromString(@"personEat")) {
        /**
         *  参数1:给哪个类动态添加方法
         *  添加方法的方法编号
         *  添加方法的函数实现(函数地址)
         *  函数的类型, (返回值+参数类型) "v":void "@":对象->self  ":":表示SEL->_cmd
         */
        class_addMethod(self, sel, (IMP)personEat, "v@:");
    }
    return YES;
}


@end
